/**
 * 
 */
package xiaojian.toolkit.bean.tlv.decode.decoders;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import xiaojian.toolkit.bean.tlv.annotation.TlvType;
import xiaojian.toolkit.bean.tlv.decode.TLVDecodeContext;
import xiaojian.toolkit.bean.tlv.decode.TLVDecoder;

import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;


/**
 * @author hp
 *
 */
public class StringTLVDecoder implements TLVDecoder {

    private static final Logger logger = LoggerFactory.getLogger(StringTLVDecoder.class);
    
	/**
	 * @see com.skymobi.bean.tlv.TLVDecoder#decode(int, byte[], com.skymobi.bean.tlv.decode.TLVDecodeContext)
	 */
	public Object decode(int tlvLength, byte[] tlvValue, TLVDecodeContext ctx) {
        String charset = "UTF-8";
        boolean trimString = false;
        Field field = ctx.getValueField();
        if ( null != field ) {
	        TlvType attr = field.getAnnotation(TlvType.class);
	        if ( null != attr ) {
	        	if ( !"".equals( attr.charset() ) ) {
	        		charset = attr.charset();
	        	}
                trimString = attr.trimString();
	        }
        }
		try {
            String result = new String(tlvValue, 0, tlvLength, charset);
			return trimString ? result.trim() : result;
		} catch (UnsupportedEncodingException e) {
        	logger.error("StringTLVDecoder:", e);
		}
		
		return	null;
	}
	
	public Class<?>[] getFieldType() {
		return new Class<?>[]{String.class};
	}

}
